import os
import random
from typing import Optional

# 使用老版本 SDK：alibabacloud_dysmsapi20170525
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi.models import Config
from alibabacloud_dysmsapi20170525.models import SendSmsRequest
from xhlib.xhsms import SMS_ACCESS_KEY_ID,SMS_ACCESS_KEY_SECRET,SMS_SMS_ENDPOINT,SMS_SIGN_NAME
# --- Configuration for Alibaba Cloud SMS ---

TEMPLATE_CODE = 'SMS_154395101'  # 模板 ID

def create_sms_client() -> Dysmsapi20170525Client:
    """
    Creates and returns an Alibaba Cloud SMS client (version 20170525).
    """
    config = Config(
        access_key_id=SMS_ACCESS_KEY_ID,
        access_key_secret=SMS_ACCESS_KEY_SECRET
    )
    # 设置 endpoint（不建议设置 region_id）
    config.endpoint = SMS_SMS_ENDPOINT
    return Dysmsapi20170525Client(config)

def generate_verification_code() -> str:
    """
    Generates a 6-digit random numeric verification code.
    """
    return str(random.randint(100000, 999999))

def send_sms_code(phone_number: str, code: str) -> None:
    """
    Sends a verification code to the specified phone number using Alibaba Cloud SMS.
    """
    try:
        client = create_sms_client()

        # 构建模板参数
        template_param = f'{{"code":"{code}"}}'

        # 创建请求对象
        send_sms_request = SendSmsRequest(
            phone_numbers=phone_number,
            sign_name=SMS_SIGN_NAME,
            template_code=TEMPLATE_CODE,
            template_param=template_param
        )

        # 发送短信
        response = client.send_sms(send_sms_request)
        print(f"SMS send response: {response.body.to_map()}")
        print(f"SMS sent to {phone_number} with code: {code}")

    except Exception as e:
        print(f"Error sending SMS: {e}")

if __name__ == "__main__":
    phone_number = "15184432110"  # 替换为你的测试手机号
    code = generate_verification_code()
    send_sms_code(phone_number, code)